<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus02.html">Previous Chapter</a>
    <li> <a href="cplusplus04.html">Next Chapter</a>
</ul>
<hr>
<a name="FirstImpression"></a><a name="l31"></a>
<h1>Chapter 3: A first impression of C++</h1>
<a name="first"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="first/first"></a>In this chapter <strong>C++</strong> is further explored. The possibility to
declare functions in <code>struct</code>s is illustrated in various examples. The
concept of a <code>class</code> is introduced.
<p>
<a name="l32"></a>
<h2>3.1: More extensions to C in C++</h2>
<a name="first/more"></a>Before we continue with the `real' object-approach to programming, we first
introduce some extensions to the <strong>C</strong> programming language: not mere
differences between <strong>C</strong> and <strong>C++</strong>, but syntactical constructs and keywords
not found in <strong>C</strong>.
<p>
<a name="l33"></a>
<h3>3.1.1: The scope resolution operator ::</h3>
    <a name="first/scope"></a><strong>C++</strong> introduces a number of new operators, among which the
<a name="an151"></a>
scope resolution operator (<a name="an152"></a>
<code>::</code>). This operator can be
used in situations where a global variable exists having the same name as a
local variable:
        <pre>
    #include &lt;stdio.h&gt;

    int counter = 50;                   // global variable

    int main()
    {
        for (register int counter = 1;  // this refers to the
             counter &lt; 10;              // local variable
             counter++)
        {
            printf("%d\n",
                    ::counter           // global variable
                    /                   // divided by
                    counter);           // local variable
        }
        return 0;
    }
</pre>
    In this code fragment the scope operator is used to address a global
variable instead of the local variable with the same name. In <strong>C++</strong> the
scope operator is used extensively, but it is seldomly used to reach a global
variable shadowed by an identically named local variable. Its main purpose
will be described in chapter <a href="cplusplus06.html#Classes">6</a>.
<p>
<a name="CoutCinCerr"></a><a name="l34"></a>
<h3>3.1.2: `cout', `cin', and `cerr'</h3>
    <a name="first/cout"></a>Analogous to <strong>C</strong>, <strong>C++</strong> defines standard input- and output streams
which are opened when a program is executed. The streams are:
    <ul>
    <li> <a name="an153"></a>
<code>cout</code>, analogous to <a name="an154"></a>
<code>stdout</code>,
    <li> <a name="an155"></a>
<code>cin</code>, analogous to <a name="an156"></a>
<code>stdin</code>,
    <li> <a name="an157"></a>
<code>cerr</code>, analogous to <a name="an158"></a>
<code>stderr</code>.
    </ul>
    Syntactically these streams are not used as functions: instead, data are
written to streams or read from them using the operators <<, called
the <a name="an159"></a>
<em>insertion operator</em> and >>, called the
<a name="an160"></a>
<em>extraction operator</em>.  This is illustrated in the next example:
        <pre>
    #include &lt;iostream&gt;

    using namespace std;

    int main()
    {
        int     ival;
        char    sval[30];

        cout &lt;&lt; "Enter a number:" &lt;&lt; endl;
        cin &gt;&gt; ival;
        cout &lt;&lt; "And now a string:" &lt;&lt; endl;
        cin &gt;&gt; sval;

        cout &lt;&lt; "The number is: " &lt;&lt; ival &lt;&lt; endl
             &lt;&lt; "And the string is: " &lt;&lt; sval &lt;&lt; endl;
    }
</pre>
    This program reads a number and a string from the <code>cin</code> stream (usually
the keyboard) and prints these data to <code>cout</code>. With respect to streams,
please note:
    <ul>
    <li> The standard streams are declared in the header file <a name="an161"></a>
<code>iostream</code>. In
the examples in the Annotations this header file is often not mentioned
explicitly. Nonetheless, it <em>must</em> be included (either directly or
indirectly) when these streams are used. Comparable to the use of the <code>using
namespace std;</code> clause, the reader is expected to <code>#include &lt;iostream&gt;</code> with
all the examples in which the standard streams are used.
    <li> The streams <code>cout</code>, <code>cin</code> and <code>cerr</code> are variables of so-called
<a name="an162"></a>
<em>class</em>-types. Such variables are commonly called <a name="an163"></a>
<em>object</em><em>s</em>. Classes
are discussed in detail in chapter <a href="cplusplus06.html#Classes">6</a> and are used extensively in
<strong>C++</strong>.
    <li> The stream <code>cin</code> extracts data from a stream and copies the
extracted information to variables (e.g., <code>ival</code> in the above example) using
the extraction operator (two consecutive <code>&gt;</code> characters: >>). We will
describe later how operators in <strong>C++</strong> can perform quite different actions
than what they are defined to do by the language, as is the case
here. Function overloading has already been mentioned.  In <strong>C++</strong>
<em>operators</em> can also have multiple definitions, which is called <em>operator
overloading</em>.
    <li> The operators which manipulate <code>cin</code>, <code>cout</code> and <code>cerr</code> (i.e.,
>> and <<) also manipulate variables of different types. In the
above example <code>cout</code> << <code>ival</code> results in the printing of an integer
value, whereas <code>cout</code> << <code>"Enter a number"</code> results in the printing
of a string. The actions of the operators therefore depend on the types of
supplied variables.
    <li> The <a name="an164"></a>
<em>extraction operator</em> (>>) performs a so called
        <a name="an165"></a>
<em>type safe</em> assignment to a variable by `extracting' its value from
a text-stream. Normally, the extraction operator will skip all
        <a name="an166"></a>
<em>white space</em> <a name="an167"></a>
 characters that precede
the values to be extracted.
    <li> Special <a name="an168"></a>
symbolic constants are used for special situations. The
termination of a line written by <code>cout</code> is usually realized by inserting the
<a name="an169"></a>
<code>endl</code> symbol, rather than the string <code>"\n"</code>.
    </ul>
    The streams <code>cin</code>, <code>cout</code> and <code>cerr</code> are not part of the
<strong>C++</strong> grammar, as defined in the compiler which parses source files. The
streams are part of the definitions in the header file <code>iostream</code>. This is
comparable to the fact that functions like <code>printf()</code> are not part of the
<strong>C</strong> grammar, but were originally written by people who considered such
functions important and collected them in a run-time library.
<p>
Whether a program uses the old-style functions like <code>printf()</code> and
<code>scanf()</code> or whether it employs the new-style streams is a matter of taste.
Both styles can even be mixed. A number of advantages and disadvantages is
given below:
    <ul>
    <li> Compared to the standard <code>C</code> functions <code>printf()</code> and
<code>scanf()</code>, the usage of the insertion and extraction operators is more
<a name="an170"></a>
<em>type-safe</em>.  The format strings which are used with <code>printf()</code> and
<code>scanf()</code> can define wrong format specifiers for their arguments, for which
the compiler sometimes can't warn. In contrast, argument checking with
<code>cin</code>, <code>cout</code> and <code>cerr</code> is performed by the compiler. Consequently it
isn't possible to err by providing an <code>int</code> argument in places where,
according to the format string, a string argument should appear.
    <li> The functions <code>printf()</code> and <code>scanf()</code>, and other functions which
use format strings, in fact implement a mini-language which is interpreted at
run-time. In contrast, the <code>C++</code> compiler knows exactly which in- or
output action to perform given which argument.
    <li> The usage of the left-shift and right-shift operators in the context
of the streams does illustrate the possibilities of <code>C++</code>.  Again, it
requires a little getting used to, ascending from <strong>C</strong>, but after that these
overloaded operators feel rather comfortably.
    <li> <code>Iostreams</code> are <em>extensible</em>: new functionality can easily be
added to existing functionality, a phenomenon called
<em>inheritance</em>. Inheritance is discussed in detail in chapter
<a href="cplusplus13.html#INHERITANCE">13</a>.
    </ul>
    The <em>iostream library</em> has a lot more to offer than just <code>cin, cout</code>
and <code>cerr</code>. In chapter <a href="cplusplus05.html#IOStreams">5</a> <em>iostreams</em> will be covered in
greater detail. Even though <a name="an171"></a>
<code>printf()</code> and friends can still be used in
<strong>C++</strong> programs, streams are practically replacing the old-style <strong>C</strong>
<code>I/O</code> functions like <code>printf()</code>. If you <em>think</em> you still need to use
<code>printf()</code> and related functions, think again: in that case you've probably
not yet completely grasped the possibilities of stream objects.
<p>
<a name="ConstRule"></a><a name="l35"></a>
<h3>3.1.3: The keyword `const'</h3>
    <a name="first/const"></a>The keyword <a name="an172"></a>
<code>const</code> is very often seen in <strong>C++</strong> programs. Although
<code>const</code> is part of the <strong>C</strong> grammar, in <strong>C</strong> <code>const</code> is used much less
frequently.
<p>
The <code>const</code> keyword is a modifier which states that the value of a variable
or of an argument may not be modified. In the following example the intent is
to  change the value of a variable <code>ival</code>, which fails:
        <pre>
    int main()
    {
        int const ival = 3;     // a constant int
                                // initialized to 3

        ival = 4;               // assignment produces
                                // an error message
    }
</pre>
    This example shows how <code>ival</code> may be initialized to a given value in its
definition; attempts to change the value later (in an assignment) are not
permitted.
<p>
Variables which are declared <code>const</code> can, in contrast to <strong>C</strong>, be used as
the specification of the size of an array, as in the following example:
        <pre>
    int const size = 20;
    char buf[size];             // 20 chars big
</pre>
    Another use of the keyword <code>const</code> is seen in the declaration of
pointers, e.g., in pointer-arguments. In the declaration
        <pre>
    char const *buf;
</pre>
    <code>buf</code> is a pointer variable, which points to <code>char</code>s. Whatever is
pointed to by <code>buf</code> may not be changed: the <code>char</code>s are declared as
<code>const</code>. The pointer <code>buf</code> itself however may be changed. A statement like
<code>*buf = 'a';</code> is therefore not allowed, while <code>buf++</code> is.
<p>
In the declaration
        <pre>
    char *const buf;
</pre>
    <code>buf</code> itself is a <code>const</code> pointer which may not be changed. Whatever
<code>char</code>s are pointed to by <code>buf</code> may be changed at will.
<p>
Finally, the declaration
        <pre>
    char const *const buf;
</pre>
    is also possible; here, neither the pointer nor what it points to may be
changed.
<p>
The <a name="an173"></a>
rule of thumb for the placement of the keyword <code>const</code> is the
following: whatever occurs to the <em>left</em> to the keyword may not be changed.
<p>
Although simple, this rule of thumb is not often used. For example,
    <a name="an174"></a>

    Bjarne Stroustrup states (in
    <a name="an175"></a>

    <a target=_top href="http://www.research.att.com/~bs/bs_faq2.html#constplacement">http://www.research.att.com/~bs/bs_faq2.html#constplacement</a>):
    <blockquote>
    <em>Should I put "const" before or after the type?</em>
<p>
<em>I put it before, but that's a matter of taste. "const T" and "T const"
were always (both) allowed and equivalent. For example:</em>
        <pre>
    const int a = 1;        // ok
    int const b = 2;        // also ok
</pre>
    <em>My guess is that using the first version will confuse fewer programmers
(``is more idiomatic'').</em>
    </blockquote>
    Below we'll see an example where applying this simple `before' placement
rule for the keyword <code>const</code> produces unexpected (i.e., unwanted)
results. Apart from that, the `idiomatic' before-placement conflicts with the
notion of <a name="an176"></a>
<em>const functions</em>, which we will encounter in section
<a href="cplusplus06.html#ConstFunctions">6.2</a>, where the keyword <code>const</code> is also written behind the
name of the function.
<p>
The definition or declaration in which <code>const</code> is used should be read from
the variable or function identifier back to the type indentifier:
        <blockquote>
    ``Buf is a const pointer to const characters''
        </blockquote>
    This rule of thumb is especially useful in cases where confusion may
occur.  In examples of <strong>C++</strong> code, one often encounters the reverse:
<code>const</code> <em>preceding</em> what should not be altered. That this may result in
sloppy code is indicated by our second example above:
        <pre>
    char const *buf;
</pre>
    What must remain constant here? According to the sloppy interpretation,
the pointer cannot be altered (since <code>const</code> precedes the pointer). In
fact, the charvalues are the constant entities here, as will be clear when we
try to compile the following program:
        <pre>
    int main()
    {
        char const *buf = "hello";

        buf++;                  // accepted by the compiler
        *buf = 'u';             // rejected by the compiler

        return 0;
    }
</pre>
    Compilation fails on the statement <code>*buf = 'u';</code>, <em>not</em> on the
statement <code>buf++</code>.
<p>
<a name="an177"></a>

    <a name="an178"></a>

    <a name="an179"></a>
Marshall Cline's
    <a target=_top href="http://www.parashift.com/c++-faq-lite/const-correctness.html">C++ FAQ</a> gives the
same rule (paragraph 18.5) , in a similar context:
    <blockquote><em>
    [18.5] What's the difference between "const Fred* p", "Fred* const p" and
"const Fred* const p"?</em>
<p>
<em>You have to read pointer declarations right-to-left.</em>
    </blockquote>
    Marshal Cline's advice might be improved, though: You should start to read
pointer definitions (and declarations) at the variable name, reading as far as
possible to the definition's end. Once a closing parenthesis is seen, reading
continues backwards from the initial point of reading, from right-to-left,
until the matching open-parenthesis or the very beginning of the definition is
found. For example, consider the following complex declaration:
        <pre>
    char const *(* const (*ip)[])[]
</pre>
    Here, we see:
    <ul>
    <li> the variable <code>ip</code>, being a
    <li> (reading backwards) modifiable pointer to an
    <li> (reading forward)   array of
    <li> (reading backward)  constant pointers to an
    <li> (reading forward)   array of
    <li> (reading backward)  modifiable pointers to constant characters
    </ul>
<p>
<a name="l36"></a>
<h3>3.1.4: References</h3>
    <a name="first/references"></a>In addition to the well known ways to define variables, plain variables or
pointers, <strong>C++</strong> allows
`<a name="an180"></a>
references' to be defined as synonyms for variables. A reference to a
variable is like an <em>alias</em>; the variable and the reference can
both be used in statements involving the variable:
        <pre>
    int int_value;
    int &amp;ref = int_value;
</pre>
    In the above example a variable <code>int_value</code> is defined. Subsequently a
reference <code>ref</code> is defined, which (due to its initialization) refers to the
same memory location as <code>int_value</code>. In the definition of
<code>ref</code>, the reference operator <code>&amp;</code> indicates that <code>ref</code> is not
itself an integer but a reference to one. The two statements
        <pre>
    int_value++;            // alternative 1
    ref++;                  // alternative 2
</pre>
    have the same effect, as expected. At some memory location an <code>int</code>
value is increased by one. Whether that location is called <code>int_value</code> or
<code>ref</code> does not matter.
<p>
References serve an important function in <strong>C++</strong> as a means to pass
arguments which can be modified. E.g., in standard <strong>C</strong>, a function that
increases the value of its argument by five but returns nothing
(<code>void</code>), needs a pointer parameter:
        <pre>
    void increase(int *valp)    // expects a pointer
    {                           // to an int
        *valp += 5;
    }

    int main()
    {
        int x;

        increase(&amp;x)            // the address of x is
        return 0;               // passed as argument
    }
</pre>
    This construction can <em>also</em> be used in <strong>C++</strong> but the same effect
can also be achieved using a reference:
        <pre>
    void increase(int &amp;valr)    // expects a reference
    {                           // to an int
        valr += 5;
    }

    int main()
    {
        int x;

        increase(x);            // a reference to x is
        return 0;               // passed as argument
    }
</pre>
    It can be argued whether code such as the above is clear: the statement
<code>increase</code> <code>(x)</code> in the <code>main()</code> function suggests that not <code>x</code>
itself but a <em>copy</em> is passed. Yet the value of <code>x</code> changes because of
the way <code>increase()</code> is defined.
<p>
Actually, references are implemented using pointers. So, references in
<strong>C++</strong> are just pointers, as far as the compiler is concerned.  However, the
programmer does not need to know or to bother about levels of
indirection. Nevertheless, pointers and references <em>should</em> be
distinguished: once initialized, references can never refer to another
variable, whereas the values of pointer variables can be changed, which will
result in the pointer variable pointing to another location in memory. For
example:
        <pre>
    extern int *ip;
    extern int &amp;ir;

    ip = 0;     // reassigns ip, now a 0-pointer
    ir = 0;     // ir unchanged, the int variable it refers to
                // is now 0.
</pre>
<p>
In order to prevent confusion, we suggest to adhere to the following:
    <ul>
    <li> In those situations where a called function does not alter its
arguments of primitive types, a copy of the variables can be passed:
            <pre>
        void some_func(int val)
        {
            cout &lt;&lt; val &lt;&lt; endl;
        }

        int main()
        {
            int x;

            some_func(x);       // a copy is passed, so
            return 0;           // x won't be changed
        }
</pre>
    <li> When a function changes the values of its arguments, a pointer
parameter is preferred. These pointer parameters should preferably be the
initial parameters of the function. This is called `return by argument'.
            <pre>
        void by_pointer(int *valp)
        {
            *valp += 5;
        }
</pre>
    <li> When a function doesn't change the value of its class- or struct-type
arguments, or if the modification of the argument is a trivial side-effect
(e.g., the argument is a stream), references can be used. Const-references
should be used if the function does not modify the argument:
            <pre>
        void by_reference(string const &amp;str)
        {
            cout &lt;&lt; str;
        }

        int main ()
        {
            int x = 7;
            string str("hello");

            by_pointer(&amp;x);         // a pointer is passed
            by_reference(str);      // str is not altered
            return 0;               // x might be changed
        }
</pre>
    References play an important role in cases where the argument will not be
changed by the function, but where it is undesirable to use the argument to
initialize the parameter. Such a situation occurs when a large variable, e.g.,
a <code>struct</code>, is passed as argument, or is returned by the function.  In these
cases the copying operation tends to become a significant factor, as the
entire structure must be copied. So, in those cases references are
preferred. If the argument isn't changed by the function, or if the caller
shouldn't change the returned information, the use of the <code>const</code> keyword
should be used. Consider the following example:
        <pre>
    struct Person                   // some large structure
    {
        char    name[80],
        char    address[90];
        double  salary;
    };

    Person person[50];          // database of persons
                                // printperson expects a
    void printperson (Person const &amp;p)
    {                           // reference to a structure
                                // but won't change it
        cout &lt;&lt; "Name: " &lt;&lt; p.name &lt;&lt; endl &lt;&lt;
                "Address: " &lt;&lt; p.address &lt;&lt; endl;

    }
                                // get a person by indexvalue
    Person const &amp;person(int index)
    {
        return person[index];   // a reference is returned,
    }                           // not a copy of person[index]

    int main()
    {
        Person boss;

        printperson (boss);     // no pointer is passed,
                                // so variable won't be
                                // altered by the function
        printperson(person(5));
                                // references, not copies
                                // are passed here
        return 0;
    }
</pre>
    <li> Furthermore, it should be noted that there is yet another reason to
use references when passing objects as function arguments: when passing a
reference to an object, the activation of the so called <em>copy constructor</em>
is avoided. Copy constructors will be covered in chapter <a href="cplusplus07.html#MEMORY">7</a>.
    </ul>
    References may result in extremely `ugly' code. A function may
return a reference to a variable, as in the following example:
        <pre>
    int &amp;func()
    {
        static int value;
        return value;
    }
</pre>
    This allows the following constructions:
        <pre>
    func() = 20;
    func() += func();
</pre>
    It is probably superfluous to note that such constructions should normally
not be used. Nonetheless, there are situations where it is useful to return a
reference.  We have actually already seen an example of this phenomenon at our
previous discussion of the streams. In a statement like <code>cout</code> <<
<code>"Hello"</code> << <code>endl;</code>, the insertion operator returns a reference to
<code>cout</code>. So, in this statement first the <code>"Hello"</code> is inserted into
<code>cout</code>, producing a reference to <code>cout</code>. Via this reference the <code>endl</code>
is then inserted in the <code>cout</code> object, again producing a reference to
<code>cout</code>. This latter reference is not further used.
<p>
A number of differences between pointers and references is pointed out in the
list below:
    <ul>
    <li> A reference cannot exist by itself, i.e., without something to
refer to. A declaration of a reference like
        <center><code>int &amp;ref;</code></center>
    is not allowed; what would <code>ref</code> refer to?
    <li> References can, however, be declared as <code>external</code>.  These
references were initialized elsewhere.
    <li> References may exist as parameters of functions: they are initialized
when the function is called.
    <li> References may be used in the return types of functions. In those
cases the function determines to what the return value will refer.
    <li> References may be used as data members of classes. We will return
to this usage later.
    <li> In contrast, pointers are variables by themselves. They point at
something concrete or just ``at nothing''.
    <li> References are aliases for other variables and cannot be re-aliased
to another variable. Once a reference is defined, it refers to its particular
variable.
    <li> In contrast, pointers can be reassigned to point to different
variables.
    <li> When an address-of operator <code>&amp;</code> is used with a reference, the
expression yields the address of the variable to which the reference
applies. In contrast, ordinary pointers are variables themselves, so the
address of a pointer variable has nothing to do with the address of the
variable pointed to.
    </ul>
<p>
<a name="FunctionsInStructs"></a><a name="l37"></a>
<h2>3.2: Functions as part of structs</h2>
<a name="first/structs"></a>Earlier it was mentioned that functions can be part of <code>struct</code>s (see
section <a href="cplusplus02.html#FunctionInStruct">2.5.14</a>).  Such functions are called
    <a name="an181"></a>
<em>member functions</em> or <a name="an182"></a>
<em>methods</em>.
This section discusses how to define such functions.
<p>
The code fragment below illustrates a <code>struct</code> having data fields for a
name and an address. A function <code>print()</code> is included in the
<code>struct</code> definition:
        <pre>
    struct Person
    {
        char name[80],
        char address[80];

        void print();
    };
</pre>
    The member function <code>print()</code> is defined using the structure name
(<code>Person</code>) and the scope resolution operator (<code>::</code>):
        <pre>
    void Person::print()
    {
        cout &lt;&lt; "Name:      " &lt;&lt; name &lt;&lt; endl
                "Address:   " &lt;&lt; address&lt;&lt; endl;
    }
</pre>
    In the definition of this member function, the function name is preceded
by the <code>struct</code> name followed by <code>::</code>. The code of the function shows how
the fields of the <code>struct</code> can be addressed without using the type name: in
this example the function <code>print()</code> prints a variable <code>name</code>. Since
<code>print()</code> is a part of the <code>struct</code> <code>person</code>, the variable <code>name</code>
implicitly refers to the same type.
<p>
This <code>struct</code> could be used as follows:
        <pre>
    Person p;

    strcpy(p.name, "Karel");
    strcpy(p.address, "Rietveldlaan 37");
    p.print();
</pre>
    The advantage of member functions lies in the fact that the called
function can automatically address the data fields of the structure for which
it was invoked. As such, in the statement <code>p.print()</code> the structure <code>p</code> is
the `substrate': the variables <code>name</code> and <code>address</code> which are used in the
code of <code>print()</code> refer to the same <code>struct p</code>.
<p>
<a name="l38"></a>
<h2>3.3: Several new data types</h2>
<a name="first/datatypes"></a>In <strong>C</strong> the following <a name="an183"></a>
basic data types are available: <code>void, char,
short, int, long, float</code> and <code>double</code>. <strong>C++</strong> extends these basic
types with several new types: the types <a name="an184"></a>
<code>bool</code>, <a name="an185"></a>
<code>wchar_t</code>, <a name="an186"></a>
<code>long long</code>
and <a name="an187"></a>
<code>long double</code> (Cf. <a name="an188"></a>
ANSI/ISO draft (1995), par. 27.6.2.4.1 for
examples of these very long types).  The type <a name="an189"></a>
<code>long long</code> is merely a
double-long <code>long</code> datatype. The type <a name="an190"></a>
<code>long double</code> is merely a
double-long <code>double</code> datatype. Apart from these basic types a standard type
<code>string</code> is available. The datatypes <code>bool</code>, and <code>wchar_t</code> are covered
in the following sections, the datatype <code>string</code> is covered in chapter
<a href="cplusplus04.html#String">4</a>.
<p>
Now that these new types are introduced, let's refresh your
memory about <em>letters</em> that can be used in <a name="an191"></a>
<em>literal constants</em> of various
    <a name="an192"></a>

types. They are:
    <ul>
    <li> <code>E</code> or <code>e</code>: <a name="an193"></a>
 the
<a name="an194"></a>
<em>exponentiation</em> character in floating point literal values. For example:
<code>1.23E+3</code>. Here, <code>E</code> should be pronounced (and iterpreted) as: <em>times 10
to the power</em>. Therefore, <code>1.23E+3</code> represents the value <code>1230</code>.
    <li> <code>F</code> <a name="an195"></a>
 can be used as <em>postfix</em> to a
non-integral numerical constant to indicate a value of type <code>float</code>, rather
than <code>double</code>, which is the default. For example: <code>12.F</code> (the dot
transforms 12 into a floating point value); <code>1.23E+3F</code> (see the previous
example. <code>1.23E+3</code> is a <code>double</code> value, whereas <code>1.23E+3F</code> is a
<code>float</code> value).
    <li> <code>L</code> <a name="an196"></a>
 can be used as <em>prefix</em> to
indicate a character string whose elements are <code>wchar_t</code>-type
characters. For example: <code>L"hello world"</code>.
    <li> <code>L</code> <a name="an197"></a>
 can be used as <em>postfix</em> to an
integral value to indicate a value of type <code>long</code>, rather than <code>int</code>,
which is the default. Note that there is no letter indicating a <code>short</code>
type. For that a <code>static_cast&lt;short&gt;()</code> must be used.
    <li> <code>U</code> <a name="an198"></a>
 can be used as <em>postfix</em> to an
integral value to indicate an <code>unsigned</code>  value, rather than an <code>int</code>.
It may also be combined with the postfix <code>L</code> to produce an <code>unsigned long
int</code> value.
    </ul>
<p>
<a name="BOOL"></a><a name="l39"></a>
<h3>3.3.1: The data type `bool'</h3>
    <a name="first/bool"></a>In <strong>C</strong> the following basic data types are available: <code>void, char, int,
float</code> and <code>double</code>. <strong>C++</strong> extends these five basic types with several
extra types. In this section the type <a name="an199"></a>
<code>bool</code> is introduced.
<p>
The type <code>bool</code> represents boolean (logical) values, for which the (now
reserved) values <a name="an200"></a>
<code>true</code> and <a name="an201"></a>
<code>false</code> may be used. Apart from these reserved
values, integral values may also be assigned to variables of type <code>bool</code>,
which are then implicitly converted to <code>true</code> and <code>false</code> according to the
following <a name="an202"></a>
conversion rules (assume <code>intValue</code> is an <code>int</code>-variable, and
<code>boolValue</code> is a <code>bool</code>-variable):
        <pre>
        // from int to bool:
    boolValue = intValue ? true : false;

        // from bool to int:

    intValue = boolValue ? 1 : 0;
</pre>
    Furthermore, when <code>bool</code> values are inserted into, e.g., <code>cout</code>, then
<code>1</code> is written for <code>true</code> values, and <code>0</code> is written for <code>false</code>
values. Consider the following example:
        <pre>
    cout &lt;&lt; "A true value: "  &lt;&lt; true &lt;&lt; endl
         &lt;&lt; "A false value: " &lt;&lt; false &lt;&lt; endl;
</pre>
    The <code>bool</code> data type is found in other programming languages as
well. <strong>Pascal</strong> has its type <code>Boolean</code>, and <strong>Java</strong> has a <code>boolean</code>
type. Different from these languages, <strong>C++</strong>'s type <code>bool</code> acts like a kind
of <code>int</code> type: it's primarily a documentation-improving type, having just
two values <code>true</code> and <code>false</code>. Actually, these values can be interpreted
as <code>enum</code> values for <code>1</code> and <code>0</code>. Doing so would neglect the philosophy
behind the <code>bool</code> data type, but nevertheless: assigning <code>true</code> to an
<code>int</code> variable neither produces warnings nor errors.
<p>
Using the <code>bool</code>-type is generally more intuitively clear than using
<code>int</code>. Consider the following prototypes:
        <pre>
    bool exists(char const *fileName);  // (1)
    int  exists(char const *fileName);  // (2)
</pre>
    For the first prototype <code>(1)</code>, most people will expect the function to
return <code>true</code> if the given filename is the name of an existing
file. However, using the second prototype some ambiguity arises: intuitively
the return value 1 is appealing, as it leads to constructions like
        <pre>
    if (exists("myfile"))
        cout &lt;&lt; "myfile exists";
</pre>
    On the other hand, many functions (like <a name="an203"></a>
<code>access()</code>, <a name="an204"></a>
<code>stat()</code>, etc.)
return <code>0</code> to indicate a successful operation, reserving other values to
indicate various types of errors.
<p>
As a rule of thumb I suggest the following: if a function should
inform its caller about the success or failure of its task, let the function
return a <code>bool</code> value. If the function should return success or various
types of errors, let the function return <em>enum</em> values, documenting the
situation when the function returns. Only when the function returns a
meaningful integral value (like the sum of two <code>int</code> values), let the
function return an <code>int</code> value.
<p>
<a name="WCHAR"></a><a name="l40"></a>
<h3>3.3.2: The data type `wchar_t'</h3>
    <a name="first/wchar"></a>The <a name="an205"></a>
<code>wchar_t</code> type is an extension of the <code>char</code> basic type, to accomodate
<em>wide</em> character values, such as the <a name="an206"></a>
<em>Unicode</em> character set.
The <a name="an207"></a>
 <a name="an208"></a>
<code>g++</code> compiler (version 2.95 or beyond) reports
    <a name="an209"></a>
<code>sizeof(wchar_t)</code> as 4, which easily accomodates all
65,536 different <em>Unicode</em> character values.
<p>
Note that a programming language like <strong>Java</strong> has a data type <code>char</code> that
is comparable to <strong>C++</strong>'s <code>wchar_t</code> type. <strong>Java</strong>'s <code>char</code> type is
2 bytes wide, though. On the other hand, <strong>Java</strong>'s <code>byte</code> data
type is comparable to <strong>C++</strong>'s <code>char</code> type: one byte. Very convenient....
<p>
<a name="l41"></a>
<h3>3.3.3: The data type `size_t'</h3>
    <a name="first/sizet"></a>The <a name="an210"></a>
<code>size_t</code> type is not really a built-in primitive data type, but a data
type that is promoted by <a name="an211"></a>
<strong>POSIX</strong> as a typename to be used for non-negative 
integral values. It is not a specific <strong>C++</strong> type, but also available in,
e.g., <strong>C</strong>. It should be used instead of <a name="an212"></a>
<code>unsigned int</code>. Usually it is
defined implictly when a system header file is included. The header file
`officially' defining <code>size_t</code> in the context of <strong>C++</strong> is <a name="an213"></a>
<code>cstddef</code>.
<p>
Using <code>size_t</code> has the advantage of being a <em>conceptual</em> type, rather than
a standard type that is then modified by a modifier. Thus, it improves 
the self-documenting value of source code. 
<p>
The type <code>size_t</code> should be used in all situations where non-negative
integral values are intended. Sometimes functions explictly require
<code>unsigned int</code> to be used. E.g., on <a name="an214"></a>
<code>amd</code>-architectures the <a name="an215"></a>
X-windows
function <a name="an216"></a>
<code>XQueryPointer</code> explicitly requires a pointer to a <code>unsigned int</code>
variable as one of its arguments. In this particular situation a pointer to a
<code>size_t</code> variable can't be used. This situation is exceptional,
though. Usually a <code>size_t</code> can (and should) be used where unsigned values
are intended.
<p>
Other useful bit-represented types also exists. E.g., <a name="an217"></a>
<code>uns32_t</code> is
guaranteerd to hold 32-bits unsigned values. Analogously, <a name="an218"></a>
<code>int32_t</code> holds
32-bits signed values. Corresponding types exist for 8, 16 and 64 bits
values. These types are defined in the header file <a name="an219"></a>
<code>stdint.h</code>.
<p>
<a name="l42"></a>
<h2>3.4: Keywords in C++</h2>
<a name="first/keywords"></a><strong>C++</strong>'s  <a name="an220"></a>
keywords are a superset of <strong>C</strong>'s  keywords. Here is a
list of all keywords of the language:
        <pre>
   and        const     float         operator static_cast    using
and_eq   const_cast       for               or      struct  virtual
   asm     continue    friend            or_eq      switch     void
  auto      default      goto          private    template volatile
bitand       delete        if        protected        this  wchar_t
 bitor           do    inline           public       throw    while
  bool       double       int         register        true      xor
 break dynamic_cast      long reinterpret_cast         try   xor_eq
  case         else   mutable           return     typedef
 catch         enum namespace            short      typeid
  char     explicit       new           signed    typename
 class       extern       not           sizeof       union
 compl        false    not_eq           static    unsigned
</pre>
    Note the <a name="an221"></a>
<em>operator keywords</em>: <code>and, and_eq, bitand, bitor, compl,
not, not_eq, or, or_eq, xor</code> and <code>xor_eq</code> are symbolic alternatives for,
respectively, <code>&amp;&amp;, &amp;=, &amp;, |, ~, !, !=, ||, |=, ^</code> and <code>^=</code>.
<p>
<a name="l43"></a>
<h2>3.5: Data hiding: public, private and class</h2>
<a name="first/public"></a>As mentioned before (see section <a href="cplusplus02.html#Pretensions">2.3</a>), <strong>C++</strong>
contains special syntactical possibilities to implement <a name="an222"></a>
data hiding. Data
hiding is the ability of a part of a program to hide its data from other parts;
thus avoiding improper addressing or name collisions.
<p>
<strong>C++</strong> has three special keywords which are related to data hiding:
<a name="an223"></a>
<code>private</code>, <a name="an224"></a>
<code>protected</code> and <a name="an225"></a>
<code>public</code>. These keywords can be used in the
definition of a <code>struct</code>. The keyword <code>public</code> defines all subsequent
fields of a structure as accessible by all code; the keyword <code>private</code>
defines all subsequent fields as only accessible by the code which is part of
the <code>struct</code> (i.e., only accessible to its member functions). The keyword
<code>protected</code> is discussed in chapter <a href="cplusplus13.html#INHERITANCE">13</a>, and is beyond the
scope of the current discussion.
<p>
In a <code>struct</code> all fields are <code>public</code>, unless explicitly stated otherwise.
Using this knowledge we can expand the <code>struct</code> <code>Person</code>:
        <pre>
    struct Person
    {
        private:
            char d_name[80];
            char d_address[80];
        public:
            void setName(char const *n);
            void setAddress(char const *a);
            void print();
            char const *name();
            char const *address();
    };
</pre>
    The data fields <code>d_name</code> and <code>d_address</code> are only accessible to the
member functions which are defined in the <code>struct</code>: these are the functions
<code>setName()</code>, <code>setAddress()</code> etc.. This results from the fact
that the fields <code>d_name</code> and <code>d_address</code> are preceded by the
keyword <code>private</code>. As an illustration consider the following code fragment:
        <pre>
    Person x;

    x.setName("Frank");         // ok, setName() is public
    strcpy(x.d_name, "Knarf");  // error, name is private
</pre>
    Data hiding is realized as follows: the
actual data of a <code>struct</code> <code>Person</code> are mentioned in the structure
definition. The data are accessed by the outside world using special functions,
which are also part of the definition. These member functions control all
traffic between the data fields and other parts of the program and are
therefore also called `interface' functions.  The data hiding which is thus
realized is illustrated in Figure <a href="cplusplus03.html#datahiding">2</a>.
        <a name="datahiding"></a><p><center><img src="first/datahiding.gif" align="bottom" alt="Figure 2 is shown here."/><br>
Figure 2: Private data and public interface functions of the class Person.
</center><p><br>

    Also note that the functions <code>setName()</code> and <code>setAddress()</code> are
declared as having a <code>char const *</code> argument. This means that the functions
will not alter the strings which are supplied as their arguments.  In the same
vein, the functions <code>name()</code> and <code>address()</code> return a <code>char const *</code>:
the caller may not modify the strings to which the return values point.
<p>
Two examples of member functions of the <code>struct</code> <code>Person</code> are shown
below:
        <pre>
    void Person::setName(char const *n)
    {
        strncpy(d_name, n, 79);
        d_name[79] = 0;
    }

    char const *Person::name()
    {
        return d_name;
    }
</pre>
    In general, the power of the member functions and of the concept of data
hiding lies in the fact that the interface functions can perform special
tasks, e.g., checking the validity of the data. In the above example
<code>setName()</code> copies only up to 79 characters from its argument to the data
member <code>name</code>, thereby avoiding <a name="an226"></a>
array buffer overflow.
<p>
Another example of the concept of data hiding is the following. As an
alternative to member functions which keep their data in memory (as do the
above code examples), a runtime library could be developed with interface
functions which store their data on file. The conversion of a program which
stores <code>Person</code> structures in memory to one that stores the data on disk
would not require any modification of the program using <code>Person</code>
structures. After recompilation and linking the new object module to a new
library, the program will use the new <code>Person</code> structure.
<p>
Though data hiding can be realized with <code>structs</code>, more often (almost
always) classes are used instead. A <code>class</code> refers to the same concept as a
struct, except that a <code>class</code> uses private access by default, whereas
structs use public access by default. The definition of a <code>class</code> <code>Person</code>
would therefore look exactly as shown above, except for the fact that instead
of the keyword <code>struct</code>, <code>class</code> would be used, and the initial
<code>private:</code> clause can be omitted.  Our typographic suggestion for class
names is to use a capital character as its first character, followed by the
remainder of the name in lower case (e.g., <code>Person</code>).
<p>
<a name="l44"></a>
<h2>3.6: Structs in C vs. structs in C++</h2>
<a name="first/cvscpp"></a>Next we would like to illustrate the analogy between
<strong>C</strong> and <strong>C++</strong> as far as <code>struct</code>s are concerned. In <strong>C</strong> it is
common to define several functions to process a <code>struct</code>, which then
require a pointer to the <code>struct</code> as one of their arguments. A fragment
of an imaginary <strong>C</strong> header file is given below:
        <pre>
    // definition of a struct PERSON_
    typedef struct
    {
        char name[80];
        char address[80];
    } PERSON_;

    // some functions to manipulate PERSON_ structs

    // initialize fields with a name and address
    void initialize(PERSON_ *p, char const *nm,
                       char const *adr);

    // print information
    void print(PERSON_ const *p);

    // etc..
</pre>
    In <strong>C++</strong>, the declarations of the involved functions are placed inside
the definition of the <code>struct</code> or <code>class</code>. The argument which denotes
which <code>struct</code> is involved is no longer needed.
        <pre>
    class Person
    {
        public:
            void initialize(char const *nm, char const *adr);
            void print();
            // etc..
        private:
            char d_name[80];
            char d_address[80];
    };
</pre>
    The <code>struct</code> argument is implicit in <strong>C++</strong>. A <strong>C</strong> function call
such as:
        <pre>
    PERSON_ x;

    initialize(&amp;x, "some name", "some address");
</pre>
    becomes in <strong>C++</strong>:
        <pre>
    Person x;

    x.initialize("some name", "some address");
</pre>
<p>
<a name="Namespaces"></a><a name="l45"></a>
<h2>3.7: Namespaces</h2>
<a name="namespace/intro"></a>Imagine a math teacher who wants to develop an interactive math program. For
this program functions like <code>cos(), sin(), tan()</code> etc. are to be used
accepting arguments in degrees rather than arguments in
radians. Unfortunately, the functionname <code>cos()</code> is already in use, and that
function accepts radians as its arguments, rather than degrees.
<p>
Problems like these are usually solved by defining another name, e.g., the
function name <code>cosDegrees()</code> is defined. <strong>C++</strong> offers an alternative
solution: by allowing us to use <a name="an227"></a>
<em>namespaces</em>. Namespaces can be considered
as areas or regions in the code in which identifiers are defined which
normally won't conflict with names already defined elsewhere.
<p>
Now that the <a name="an228"></a>
ANSI/ISO standard has been implemented to a large degree in
recent compilers, the use of namespaces is more strictly enforced than in
previous versions of compilers. This has certain consequences for the setup of
<a name="an229"></a>
<code>class</code> <a name="an230"></a>
header files. At this point in the Annotations this cannot be
discussed in detail, but in section <a href="cplusplus06.html#NAMESPACEHDR">6.6.1</a> the construction of
header files using entities from namespaces is discussed.
<p>
<a name="l46"></a>
<h3>3.7.1: Defining namespaces</h3>
    <a name="namespace/defining"></a>Namespaces are defined according to the following syntax:
        <pre>
    namespace identifier
    {
        // declared or defined entities
        // (declarative region)
    }
</pre>
    The identifier used in the definition of a namespace is a standard <strong>C++</strong>
identifier.
<p>
Within the <a name="an231"></a>
<em>declarative region</em>, introduced in the above code
example, functions, variables, structs, classes and even (nested) namespaces
can be defined or declared. Namespaces cannot be defined within a block. So it
is not possible to define a namespace within, e.g., a function. However, it is
possible to define a namespace using multiple <em>namespace</em>
declarations. Namespaces are called `<em>open</em>'. This means that a namespace
<code>CppAnnotations</code> could be defined in a file <code>file1.cc</code> and also in a file
<code>file2.cc</code>. The entities defined in the <code>CppAnnotations</code> namespace of
files <code>file1.cc</code> and <code>file2.cc</code> are then united in one <code>CppAnnotations</code>
namespace region. For example:
        <pre>
    // in file1.cc
    namespace CppAnnotations
    {
        double cos(double argInDegrees)
        {
            ...
        }
    }

    // in file2.cc
    namespace CppAnnotations
    {
        double sin(double argInDegrees)
        {
            ...
        }
    }
</pre>
    Both <code>sin()</code> and <code>cos()</code> are now defined in the same
<code>CppAnnotations</code> namespace.
<p>
Namespace entities can be defined outside of their namespaces. This
topic is discussed in section <a href="cplusplus03.html#OUTSIDE">3.7.4.1</a>.
<p>
<a name="l47"></a>
<strong>3.7.1.1: Declaring entities in namespaces</strong>
        <a name="namespace/declaring"></a>    Instead of <em>defining</em> entities in a namespace, entities may also be
<em>declared</em> in a namespace. This allows us to put all the
    <a name="an232"></a>
 declarations of a namespace in a header file
which can thereupon be included in sources in which the entities of a
namespace are used. Such a header file could contain, e.g.,
        <pre>
    namespace CppAnnotations
    {
        double cos(double degrees);
        double sin(double degrees);
    }
</pre>
<p>
<a name="l48"></a>
<strong>3.7.1.2: A closed namespace</strong>
        <a name="namespace/closed"></a>Namespaces can be defined without a name. Such a namespace is anonymous
and it restricts the visibility of the defined entities to the source file in
which the <a name="an233"></a>
anonymous namespace is defined.
<p>
Entities defined in the anonymous namespace are comparable to <strong>C</strong>'s
<a name="an234"></a>
<code>static</code> functions and variables. In <strong>C++</strong> the <code>static</code> keyword can
still be used, but its use is more common in <code>class</code> definitions (see
chapter <a href="cplusplus06.html#Classes">6</a>). In situations where static variables or
functions are necessary, the use of the anonymous namespace is preferred.
<p>
The anonymous namespace is a <a name="an235"></a>
closed namespace: it is not possible to add
entities to the same anonymous namespace using different source files.
<p>
<a name="l49"></a>
<h3>3.7.2: Referring to entities</h3>
    <a name="namespace/referring"></a>Given a namespace and entities that are defined or declared in it, the
    <a name="an236"></a>
scope resolution operator can be used to refer to the entities that are
defined in that namespace. For example, to use the function <code>cos()</code> defined
in the <code>CppAnnotations</code> namespace the following code could be used:
        <pre>
    // assume the CppAnnotations namespace is declared in the
    // next header file:
    #include &lt;CppAnnotations&gt;

    int main()
    {
        cout &lt;&lt; "The cosine of 60 degrees is: " &lt;&lt;
                CppAnnotations::cos(60) &lt;&lt; endl;
    }
</pre>
    This is a rather cumbersome way to refer to the <code>cos()</code> function in the
<code>CppAnnotations</code> namespace, especially so if the function is frequently
used.
<p>
However, in these cases an <em>abbreviated</em> form (just <code>cos()</code>) can be
used by specifying a <a name="an237"></a>
<em>using-declaration</em>. Following
        <pre>
    using CppAnnotations::cos;  // note: no function prototype,
                                // just the name of the entity
                                // is required.
</pre>
    the function <code>cos()</code> will refer to the <code>cos()</code> function in the
<code>CppAnnotations</code> namespace. This implies that the standard <code>cos()</code>
function, accepting radians, cannot be used automatically anymore. The plain
scope resolution operator can be used to reach the generic <code>cos()</code> function:
        <pre>
    int main()
    {
        using CppAnnotations::cos;
        ...
        cout &lt;&lt; cos(60)         // uses CppAnnotations::cos()
            &lt;&lt; ::cos(1.5)       // uses the standard cos() function
            &lt;&lt; endl;
    }
</pre>
    Note that a <code>using</code>-declaration can be used inside a block. The
<code>using</code> declaration prevents the definition of entities having the same
name as the one used in the <code>using</code> declaration: it is not possible to
use a <code>using</code> declaration for a variable <code>value</code> in the <code>CppAnnotations</code>
namespace, and to define (or declare) an identically named object in the
block in which the <code>using</code> declaration was placed:
        <pre>
    int main()
    {
        using CppAnnotations::value;
        ...
        cout &lt;&lt; value &lt;&lt; endl;  // this uses CppAnnotations::value

        int value;              // error: value already defined.
    }
</pre>
<p>
<a name="l50"></a>
<strong>3.7.2.1: The `using' directive</strong>
        <a name="namespace/directive"></a>A generalized alternative to the <code>using</code>-declaration is the
<a name="an238"></a>
<em>using-directive</em>:
        <pre>
    using namespace CppAnnotations;
</pre>
    Following this directive, <em>all</em> entities defined in the
<code>CppAnnotations</code> namespace are used as if they where declared by <code>using</code>
declarations.
<p>
While the <code>using</code>-directive is a quick way to <a name="an239"></a>
import all the names of
the <code>CppAnnotations</code> namespace (assuming the entities are declared or
defined separately from the directive), it is at the same time a somewhat
dirty way to do so, as it is less clear which entity will be used in a
particular block of code.
<p>
If, e.g., <code>cos()</code> is defined in the <code>CppAnnotations</code> namespace, the
function <code>CppAnnotations::cos()</code> will be used when <code>cos()</code> is called in
the code. However, if <code>cos()</code> is <em>not</em> defined in the <code>CppAnnotations</code>
namespace, the standard <code>cos()</code> function will be used. The <code>using</code>
directive does not document as clearly which entity will be used as the
<code>using</code> declaration does. For this reason, the <code>using</code> directive is
somewhat deprecated.
<p>
<a name="l51"></a>
<strong>3.7.2.2: `Koenig lookup'</strong>
        <a name="namespace/koenig"></a>If <a name="an240"></a>
<em>Koenig lookup</em> were called the `Koenig principle', it could have been
the title of a new <a name="an241"></a>
Ludlum novell. However, it is not. Instead it refers to
a <strong>C++</strong> technicality.
<p>
`Koenig lookup' refers to the fact that if a function is called without
referencing a namespace, then the namespaces of its arguments are used to find
the namespace of the function. If the namespace in which the arguments are
defined contains such a function, then that function is used. This is called
the `Koenig lookup'.
<p>
In the following example this is illustrated. The function
<code>FBB::fun(FBB::Value v)</code> is defined in the <code>FBB</code> namespace. As shown, it
can be called without the explicit mentioning of a namespace:
        <pre>
    #include &lt;iostream&gt;

    namespace FBB
    {
        enum Value        // defines FBB::Value
        {
            first,
            second,
        };

        void fun(Value x)
        {
            std::cout &lt;&lt; "fun called for " &lt;&lt; x &lt;&lt; std::endl;
        }
    }

    int main()
    {
        fun(FBB::first);    // Koenig lookup: no namespace
                            // for fun()
    }
    /*
        generated output:
    fun called for 0
    */
</pre>
    Note that trying to <a name="an242"></a>
fool the compiler doesn't work: if in the
<code>namespace FBB</code> <code>Value</code> was defined as <code>typedef int Value</code> then
<code>FBB::Value</code> would have been recognized as <code>int</code>, thus causing the Koenig
lookup to fail.
<p>
As another example, consider the next program. Here there are two
namespaces involved, each defining their own <code>fun()</code> function. There is no
<a name="an243"></a>
ambiguity here, since the argument defines the namespace. So,
<code>FBB::fun()</code> is called:
        <pre>
    #include &lt;iostream&gt;

    namespace FBB
    {
        enum Value        // defines FBB::Value
        {
            first,
            second,
        };

        void fun(Value x)
        {
            std::cout &lt;&lt; "FBB::fun() called for " &lt;&lt; x &lt;&lt; std::endl;
        }
    }

    namespace ES
    {
        void fun(FBB::Value x)
        {
            std::cout &lt;&lt; "ES::fun() called for " &lt;&lt; x &lt;&lt; std::endl;
        }
    }

    int main()
    {
        fun(FBB::first);    // No ambiguity: argument determines
                            // the namespace
    }
    /*
        generated output:
    FBB::fun() called for 0
    */
</pre>
<p>
Finally, an example in which there is an ambiguity: <code>fun()</code> has two
arguments, one from each individual namespace. Here the ambiguity must be
resolved by the programmer:
        <pre>
    #include &lt;iostream&gt;

    namespace ES
    {
        enum Value        // defines ES::Value
        {
            first,
            second,
        };
    }

    namespace FBB
    {
        enum Value        // defines FBB::Value
        {
            first,
            second,
        };

        void fun(Value x, ES::Value y)
        {
            std::cout &lt;&lt; "FBB::fun() called\n";
        }
    }

    namespace ES
    {
        void fun(FBB::Value x, Value y)
        {
            std::cout &lt;&lt; "ES::fun() called\n";
        }
    }

    int main()
    {
        /*
            fun(FBB::first, ES::first); // ambiguity: must be resolved
                                        // by explicitly mentioning
                                        // the namespace
        */
        ES::fun(FBB::first, ES::first);
    }
    /*
        generated output:
    ES::fun() called
    */
</pre>
<p>
<a name="l52"></a>
<h3>3.7.3: The standard namespace</h3>
    <a name="namespace/std"></a>Many entities of the runtime available software (e.g., <code>cout, cin, cerr</code> and
the templates defined in the <em>Standard Template Library</em>, see chapter
<a href="cplusplus17.html#STL">17</a>) are now defined in the <code>std</code> namespace.
<p>
Regarding the discussion in the previous section, one should use a <code>using</code>
declaration for these entities. For example, in order to use the <code>cout</code>
stream, the code should start with something like
        <pre>
    #include &lt;iostream&gt;
    using std::cout;
</pre>
    Often, however, the identifiers that are defined in the <code>std</code> namespace
can all be accepted without much thought. Because of that, one frequently
encounters a <code>using</code> directive, rather than a <code>using</code> declaration with the
<code>std</code> namespace. So, instead of the mentioned <code>using declaration</code> a
construction like
        <pre>
    #include &lt;iostream&gt;
    using namespace std;
</pre>
    is encountered. Whether this should be encouraged is subject of some
dispute. Long <code>using</code> declarations are of course inconvenient too. So, as a
<a name="an244"></a>
rule of thumb one might decide to stick to <code>using</code> declarations, up to
the point where the list becomes impractically long, at which point a
<code>using</code> directive could be considered.
<p>
<a name="l53"></a>
<h3>3.7.4: Nesting namespaces and namespace aliasing</h3>
    <a name="namespace/nesting"></a>Namespaces can be nested. The following code shows the definition of a
<a name="an245"></a>
nested namespace:
        <pre>
    namespace CppAnnotations
    {
        namespace Virtual
        {
            void *pointer;
        }
    }
</pre>
    Now the variable <code>pointer</code> is defined in the <code>Virtual</code> namespace,
nested under the <code>CppAnnotations</code> namespace. In order to refer to this
variable, the following options are available:
    <ul>
        <li> The <em>fully qualified name</em> can be used. A fully qualified name
of an entity is a list of all the namespaces that are visited until the
definition of the entity is reached, glued together by the scope resolution
operator:
        <pre>
    int main()
    {
        CppAnnotations::Virtual::pointer = 0;
    }
</pre>
        <li> A <code>using</code> declaration for <code>CppAnnotations::Virtual</code> can be
used. Now <code>Virtual</code> can be used without any prefix, but
<code>pointer</code> must be used with the <code>Virtual::</code> prefix:
        <pre>
    ...
    using CppAnnotations::Virtual;

    int main()
    {
        Virtual::pointer = 0;
    }
</pre>
        <li> A <code>using</code> declaration for <code>CppAnnotations::Virtual::pointer</code>
can be used. Now <code>pointer</code> can be used without any prefix:
        <pre>
    ...
    using CppAnnotations::Virtual::pointer;

    int main()
    {
        pointer = 0;
    }
</pre>
        <li> A <code>using</code> directive or directives can be used:
        <pre>
    ...
    using namespace CppAnnotations::Virtual;

    int main()
    {
        pointer = 0;
    }
</pre>
    Alternatively, two separate <code>using</code> directives could have been used:
        <pre>
    ...
    using namespace CppAnnotations;
    using namespace Virtual;

    int main()
    {
        pointer = 0;
    }
</pre>
<p>
<li> A combination of <code>using</code> declarations and <code>using</code>
directives can be used. E.g., a <code>using</code> directive can be used for
the <code>CppAnnotations</code> namespace, and a <code>using</code> declaration can be used for
the <code>Virtual::pointer</code> variable:
        <pre>
    ...
    using namespace CppAnnotations;
    using Virtual::pointer;

    int main()
    {
        pointer = 0;
    }
</pre>
    </ul>
    At every <code>using</code> directive all entities of that namespace can be used
without any further prefix. If a namespace is nested, then that namespace can
also be used without any further prefix. However, the entities defined in the
nested namespace still need the nested namespace's name. Only by using a
<code>using</code> declaration or directive the qualified name of the
nested namespace can be omitted.
<p>
When <a name="an246"></a>
fully qualified names are somehow preferred and a long form like
                   <pre>
        CppAnnotations::Virtual::pointer
</pre>
    is at the same time considered too long, a <a name="an247"></a>
<em>namespace alias</em> can be
used:
                <pre>
        namespace CV = CppAnnotations::Virtual;
</pre>
<p>
This defines <code>CV</code> as an <em>alias</em> for the full name. So, to refer to the
<code>pointer</code> variable, we may now use the construction
        <pre>
    CV::pointer = 0;
</pre>
    Of course, a namespace alias itself can also be used in a
<code>using</code> declaration or directive.
<p>
<a name="OUTSIDE"></a><a name="l54"></a>
<strong>3.7.4.1: Defining entities outside of their namespaces</strong>
        <a name="namespace/outside"></a>It is not strictly necessary to <a name="an248"></a>
define members of namespaces within a
namespace region. By prefixing the member by its namespace or namespaces a
member can be defined outside of a namespace region. This may be done at the
global level, or at intermediate levels in the case of nested namespaces. So
while it is not possible to define a member of namespace <code>A</code> within the
region of namespace <code>C</code>, it is possible to define a member of namespace
<code>A::B</code> within the region of namespace <code>A</code>.
<p>
Note, however, that when a member of a namespace is defined outside of a
namespace region, it must <em>still be declared within</em> the region.
<p>
Assume the type <code>int INT8[8]</code> is defined in the
<code>CppAnnotations::Virtual</code> namespace.
<p>
Now suppose we want to define a member function <code>funny</code>, inside the
namespace <code>CppAnnotations::Virtual</code>, returning a pointer to
<code>CppAnnotations::Virtual::INT8</code>. After first defining everything
inside the <code>CppAnnotations::</code><code>Virtual</code> namespace, such a function could be
defined as follows:
        <pre>
    namespace CppAnnotations
    {
        namespace Virtual
        {
            void *pointer;

            typedef int INT8[8];

            INT8 *funny()
            {
                INT8 *ip = new INT8[1];

                for (int idx = 0; idx &lt; sizeof(INT8) / sizeof(int); ++idx)
                    (*ip)[idx] = (idx + 1) * (idx + 1);

                return ip;
            }
        }
    }
</pre>
    The function <code>funny()</code> defines an array of one <code>INT8</code> vector, and
returns its address after initializing the vector by the squares of the first
eight natural numbers.
<p>
Now the function <code>funny()</code> can be defined outside of the
<code>CppAnnotations::</code><code>Virtual</code> namespace as follows:
        <pre>
    namespace CppAnnotations
    {
        namespace Virtual
        {
            void *pointer;

            typedef int INT8[8];

            INT8 *funny();
        }
    }

    CppAnnotations::Virtual::INT8 *CppAnnotations::Virtual::funny()
    {
        INT8 *ip = new INT8[1];

        for (int idx = 0; idx &lt; sizeof(INT8) / sizeof(int); ++idx)
            (*ip)[idx] = (idx + 1) * (idx + 1);

        return ip;
    }
</pre>
    At the final code fragment note the following:
    <ul>
    <li><code>funny()</code> is declared inside of the <code>CppAnnotations::Virtual</code>
namespace.
    <li><code></code> The definition outside of the namespace region requires us to use
the fully qualified name of the function <em>and</em> of its return type.
    <li><code></code> <em>Inside</em> the block of the function <code>funny</code> we are within the
<code>CppAnnotations::</code><code>Virtual</code> namespace, so inside the function fully
qualified names (e.g., for <code>INT8</code>) are not required any more.
    </ul>
<p>
Finally, note that the function could also have been defined in the
<code>CppAnnotations</code> region. It that case the <code>Virtual</code> namespace would have
been required for the function name and its return type, while the internals
of the function would remain the same:
        <pre>
    namespace CppAnnotations
    {
        namespace Virtual
        {
            void *pointer;

            typedef int INT8[8];

            INT8 *funny();
        }

        Virtual::INT8 *Virtual::funny()
        {
            INT8 *ip = new INT8[1];

            for (int idx = 0; idx &lt; sizeof(INT8) / sizeof(int); ++idx)
                (*ip)[idx] = (idx + 1) * (idx + 1);

            return ip;
        }
    }
</pre>
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus02.html">Previous Chapter</a>
    <li> <a href="cplusplus04.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
